<template>
  <div class="template_container">
    <div class="bottom_l">
      <vxe-toolbar>
        <template #buttons>
          <el-row :gutter="20">
            <el-col :span="1.5">
              <vxe-radio-button
                v-model="selectAllLeft"
                :label="true"
                :content="!selectAllLeft ? '全选' : '取消全选'"
                :strict="false"
                size="mini"
                class="b-border"
              ></vxe-radio-button>
            </el-col>
            <el-col :span="4.5">
              <vxe-button
                @click="handleSubmitSaveAll"
                size="mini"
                v-hasPermi="['system:privileg:save']"
                >保存整站</vxe-button
              >
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>

      <vxe-table
        highlight-current-row
        highlight-hover-row
        row-key
        row-id="siteId"
        show-overflow
        ref="xTreeLeft"
        border="inner"
        :data="leftList"
        :tree-config="{
          children: 'children',
          transform: false,
          parentKey: 'parentId',
          line: true,
          iconOpen: 'el-icon-remove',
          iconClose: 'el-icon-circle-plus',
        }"
        :checkbox-config="{
          labelField: 'name',
          showHeader: false,
          checkStrictly: false,
          checkRowKeys: checkRowKeys1,
          checkMethod,
          trigger: 'default',
        }"
        class="left-table"
        @cell-click="haldleClickSite"
      >
        <vxe-column
          type="checkbox"
          tree-node
          title="可选站点列表"
          show-overflow
        >
          <template #default="{ row }">
            <span>
              <img
                src="../../../../assets/icons/png/globe.gif"
                alt=""
                style="vertical-align: bottom"
              />
              <span style="cursor: pointer; fontsize: 12px; color: #000">
                {{ row.name }}({{ row.siteId }})</span
              >
              <span
                v-if="
                  (row.channelId || row.siteId || row.net) == currentRowId &&
                  !row.root
                "
                class="activeRow-right"
              >
                <svg-icon icon-class="left" style="color: #009a94" />
              </span>
            </span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div class="bottom_r">
      <vxe-toolbar>
        <template #buttons>
          <el-row :gutter="20">
            <el-col :span="1.5" v-if="false">
              <vxe-checkbox
                v-model="menuCheckStrictly"
                content="父子联动"
              ></vxe-checkbox>
            </el-col>
            <el-col :span="1.5" v-if="false">
              <vxe-radio-button
                v-model="expend"
                :label="true"
                v-if="false"
                :content="expend ? '全部关闭' : '全部展开'"
                :strict="false"
                size="mini"
                :disabled="!siteRow"
                style="border-left-width: 1px"
              ></vxe-radio-button>
            </el-col>

            <el-col :span="1.5">
              <!-- <vxe-button @click="haldleClickSelectAll" size="mini">全选</vxe-button> -->
              <vxe-radio-button
                v-model="selectAll"
                :label="true"
                :content="!selectAll ? '全选' : '取消全选'"
                :strict="false"
                size="mini"
                :disabled="!siteRow"
                class="b-border"
              ></vxe-radio-button>
            </el-col>

            <el-col :span="4.5">
              <!-- <vxe-button size="mini" @click="$refs.xTreeRight.clearTreeExpand()">全部关闭</vxe-button> -->
              <vxe-button
                size="mini"
                @click="handleSubmitSaveOne"
                v-hasPermi="['system:privileg:save']"
                >保存模板</vxe-button
              >
              <!-- <font color='red'>注：每个站点，都必须独立保存。</font> -->
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>

      <vxe-table
        highlight-current-row
        highlight-hover-row
        row-key
        row-id="id"
        show-overflow
        ref="xTreeRight"
        border="inner"
        :data="rightList"
        :tree-config="{
          children: 'children',
          transform: false,
          parentKey: 'siteId',
          line: true,
          iconOpen: 'el-icon-remove',
          iconClose: 'el-icon-circle-plus',
        }"
        :checkbox-config="{
          labelField: 'name',
          showHeader: false,
          checkStrictly: false,
          checkRowKeys: checkRowKeys2,
          checkMethod,
        }"
        class="left-table"
        v-if="siteRow"
      >
        <vxe-column type="checkbox" tree-node show-overflow>
          <template #title="{ row }">
            <span>
              <span style="cursor: pointer; fontsize: 12px; color: #000">
                {{ siteRow.name }} 下的模板文件夹列表</span
              >
              <span style="float: right; margin: 0 10px 0 0"
                >已选择
                {{ $refs.xTreeRight.getCheckboxRecords().length }} 个栏目</span
              >
            </span>
          </template>

          <template #default="{ row }">
            <span>
              <span style="cursor: pointer; fontsize: 12px; color: #000">
                {{ row.name }} ({{ row.id }})</span
              >
            </span>
          </template>
        </vxe-column>
      </vxe-table>
      <font color="red" v-else>请先选择站点</font>
    </div>
  </div>
</template>

<script>
import { listSite } from "@/api/content/net";
import { getChannelListForTree } from "@/api/content/clounm";
import {
  savePrivilegeConfig, //部分栏目/模板/站点/
} from "@/api/system/userGroup";
import { listTemplateFile } from "@/api/template/index";

import { mapState } from "vuex";
export default {
  props: {
    TemplateFolder: {},
    TemplateWebSite: {},
  },
  data() {
    return {
      //全部展开 全部关闭
      expend: false,
      //全选。全不选
      selectAll: false,
      selectAllLeft: false,
      //是否父子联动
      menuCheckStrictly: false,
      //站点列表
      leftList: [],
      //栏目列表
      rightList: [],
      // 选中的模板文件id  已jion（’）
      templateIds: "",
      //模板文件夹 默认选中
      checkRowKeys1: [],
      checkRowKeys2: [],
      // 右侧所有栏目的id
      rightAllTemplateIds: [],
      siteRow: {},
      columnRow: {},

      //外部的站点行。
      outSiteRow: JSON.parse(sessionStorage.getItem("setSiteRow")),
      //外部的用户组行
      outGroupRow: JSON.parse(sessionStorage.getItem("userGroupRow")),
    };
  },

  components: {},
  computed: {
    ...mapState(["column"]),
    currentRowId() {
      return this.siteRow?.siteId;
    },
  },
  created() {
    this.checkRowKeysTemplateWebSiteIds();
    this.outSiteRow.siteId == 1 ? this.getSiteList() : this.getSiteList2();
  },
  mounted() {},

  watch: {
    expend(value) {
      if (value) {
        this.$refs.xTreeRight.setAllTreeExpand(true);
      } else {
        this.$refs.xTreeRight.clearTreeExpand();
        this.$nextTick(() => {
          this.$refs.xTreeRight.setTreeExpand(this.rightList[0], true);
        });
      }
    },
    selectAll(value) {
      if (value) {
        // this.menuCheckStrictly = true;
        this.$nextTick(() => {
          this.$refs.xTreeRight.setAllCheckboxRow(true);
        });
      } else {
        this.$refs.xTreeRight.setAllCheckboxRow(false);
        // this.$nextTick(() => {
        //   this.menuCheckStrictly = false;
        // });
      }
    },
    selectAllLeft(value) {
      this.$refs.xTreeLeft.setAllCheckboxRow(value ? true : false);
    },
  },

  methods: {
    //获取站点列表
    getSiteList() {
      this.siteRow = undefined;
      this.fileRow = undefined;
      this.templateList = [];
      listSite().then((res) => {
        // this.leftList = [
        //   { name: "模板库-站点列表", root: "000", children: res.data },
        // ];
        this.leftList = res.data;
      });
      // .then(() => {
      //   //展开第一个节点
      //   this.$nextTick(() => {
      //     this.$refs.xTreeLeft.setTreeExpand(this.leftList[0], true);
      //   });
      // });
    },
    //不是平台系统只显示当前站点
    getSiteList2() {
      this.leftList = [this.outSiteRow];
    },
    //点击站点行  获取栏目列表
    haldleClickSite({ row }) {
      this.expend = false;
      this.siteRow = undefined;
      this.selectAll = false;
      if (row.root || row.siteId == this.siteRow?.siteId) return;
      //重置右侧表格。可以默认选中   或者重置siteRow
      // this.rightList = [];
      //高亮当前行
      this.$refs.xTreeLeft.setCurrentRow(row);
      listTemplateFile({ siteId: row.siteId })
        .then((res) => {
          this.siteRow = row;
          this.rightAllTemplateIds = res.data.map((item) => {
            return item.id;
          });

          this.checkRowKeysTemplateFolderIds();
          // this.rightList = [
          //   {
          //     name: row.name,
          //     siteId: row.siteId,
          //     id: row.siteId,
          //     root: "111",
          //     channelId: 111,
          //     children: res.data,
          //   },
          // ];
          this.rightList = res.data;
        })
        .then(() => {
          //   //展开第一个节点
          //   this.$nextTick(() => {
          //     this.$refs.xTreeRight.setTreeExpand(this.rightList[0], true);
          //   });
        });
    },

    //保存整站
    handleSubmitSaveAll() {
      // if (selection.length == 0) {
      //   this.msgError("模板文件不能为空");
      //   return;
      // }
      let selectionId = this.$refs.xTreeLeft
        .getCheckboxRecords()
        .map((item) => item.siteId);

      this.templateIds =
        this.outSiteRow.siteId == 1
          ? [...new Set(selectionId)].join(",")
          : [...new Set(selectionId)].join(",");

      savePrivilegeConfig({
        functionIdStr: this.templateIds,
        groupId: this.column.userGroupRow.groupId,
        type: "TemplateWebSite",
      }).then((res) => {
        if (res.code == 200) {
          this.$emit("getGroupInitPrivilege");
          this.msgSuccess("保存成功");
        }
      });
    },
    //单独保存
    handleSubmitSaveOne() {
      if (!this.$refs.xTreeRight) {
        this.msgError("请选择站点，栏目");
        return;
      }
      let checkRowkey = this.checkRowKeys2;
      let arr = [];
      //先获取到非本模板文件夹的id   再concat本模板文件夹选中的id
      checkRowkey.forEach((item) => {
        if (this.rightAllTemplateIds.indexOf(item) == -1 && item != 0) {
          arr.push(item);
        }
      });
      console.log("去掉本模板文件夹的其他模板文件夹id", arr);

      // 选中的模板id
      let selectionId = this.$refs.xTreeRight
        .getCheckboxRecords()
        .map((item) => item.id);

      this.templateIds =
        this.outSiteRow.siteId == 1
          ? [...new Set(selectionId.concat(arr))].join(",")
          : [...new Set(selectionId)].join(",");

      savePrivilegeConfig({
        functionIdStr: this.templateIds || -1,
        groupId: this.column.userGroupRow.groupId,
        type: "TemplateFolder",
      }).then((res) => {
        if (res.code == 200) {
          this.$emit("getGroupInitPrivilege");
          this.msgSuccess("保存成功");
        }
      });

      // let selection = this.$refs.xTreeRight.getCheckboxRecords();
      // if (selection.length == 0) {
      //   this.msgError("模板文件不能为空");
      //   return;
      // }
      // this.templateIds = selection.map((item) => item.id).join(",");
      // savePrivilegeConfig({
      //   functionIdStr: this.templateIds,
      //   groupId: this.column.userGroupRow.groupId,
      //   type: "TemplateFolder",
      // }).then((res) => {
      //   if (res.code == 200) {
      //     this.$emit("getGroupInitPrivilege");
      //     this.msgSuccess("保存成功");
      //   }
      // });
    },

    checkRowKeysTemplateWebSiteIds() {
      let checkedKeys = this.TemplateWebSite;

      let arr = [];
      checkedKeys.forEach((v) => {
        arr.push(v.functionId);
        return;
        this.$nextTick(() => {
          this.$refs.menu.setChecked(v.functionId, true, false);
        });
        setCheckboxRow;
      });
      this.checkRowKeys1 = arr;
    },
    checkRowKeysTemplateFolderIds() {
      let checkedKeys = this.TemplateFolder;
      let arr = [];
      checkedKeys.forEach((v) => {
        arr.push(v.functionId);
        return;
        this.$nextTick(() => {
          this.$refs.menu.setChecked(v.functionId, true, false);
        });
        setCheckboxRow;
      });
      this.checkRowKeys2 = arr;
    },
    checkMethod({ row }) {
      return !row.root;
    },
  },
};
</script>

<style scoped lang="scss">
.template_container {
  height: 100%;
  display: flex;
  flex-direction: row;
}
.bottom_l {
  // overflow: auto;
  min-width: 300px;

  height: 100%;
  display: flex;
  flex-direction: column;
  .left-table {
    flex: 1;
    height: 0;
    overflow: overlay;
    overflow: auto;
  }
  ::v-deep .vxe-table--body {
  }
}
.bottom_r {
  flex: 1;
  overflow: auto;
  padding: 0 0 0 30px;
  display: flex;
  flex-direction: column;
  .left-table {
    flex: 1;
    // height: 0;
    overflow: overlay;
    overflow: auto;
  }
}
// ::v-deep .body--wrapper {
//   background: transparent !important;
// }
// ::v-deep .vxe-toolbar {
//   background: transparent !important;
// }
</style>
